//
//  ExploreMapViewViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 5/31/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "ExploreMapViewViewController.h"

@interface ExploreMapViewViewController ()

@end

@implementation ExploreMapViewViewController
@synthesize mapView;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize signalList=_signalList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setToolbarHidden:NO];
    MKUserTrackingBarButtonItem *buttonItem = [[[MKUserTrackingBarButtonItem alloc] initWithMapView:self.mapView] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    UIBarButtonItem *typeButton = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(changeMapType:)] autorelease];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    
//    [typeButton set]
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space, buttonItem,space,typeButton,nil];
//[ buttonItem release ];
//    UIBarButtonItem *butstonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back"
//                                                    style: UIBarButtonItemStyleBordered
//                                                   target: self
//                                                   action: @selector( goBack:) ];
//    self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
//    [ buttonItem release ];
    
    
    self.mapView.delegate = self;     
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.mapView setShowsUserLocation:YES];
    
    if (!_signalList) {
        self.signalList=[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    MKCoordinateRegion region=self.subSystem.region;
    if (region.center.latitude==0) {
        CLLocationCoordinate2D c={0,0};
        region.center=c;
        for (Signal *signal in self.signalList) {
            Intersection *intersection=[XMLParser getIntersection:signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
            if (intersection.intersectionCoordinate.latitude!=0) {
                region = MKCoordinateRegionMakeWithDistance(intersection.intersectionCoordinate ,5000,5000);
                break;
            }
        }
        
        
        //    = MKCoordinateRegionMakeWithDistance(self.signal.coordinate ,5000,5000);
        if (region.center.latitude==0) {
            region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate ,5000,5000);
        }
        
    }
    
    
    [self.mapView setRegion:region animated:YES];
    [self.mapView setShowsUserLocation:NO];
    for ( int i=0;i<self.signalList.count;i++) {
        Signal *signal=[self.signalList objectAtIndex:i];
//        CLLocationCoordinate2D newCoord = region.center;
        Intersection *intersection=[XMLParser getIntersection:signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        if (intersection.intersectionCoordinate.latitude!=0) {
            MapPoint *mp = [[[MapPoint alloc] initWithCoordinate:intersection.intersectionCoordinate title:signal.signalName subTitle:@""] autorelease];
            
            mp.tag=i;
            
            
            [self.mapView addAnnotation:mp];
        }
        
        
    }
    
    

    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [super viewDidUnload];
    self.agency=nil;
    self.subSystem=nil;
    self.timingPattern=nil;
    self.signalList=nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
//    [PropertyReadingWritingClass writeMapRegionToPropertyFile:mapView.region];
//    [self.navigationController setToolbarHidden:YES];
    self.subSystem.region=self.mapView.region;
    [XMLParser updateSubSystem:self.subSystem agencyID:self.agency.agencyID];
}


-(void) viewWillAppear:(BOOL)animated
{
//    [self.navigationController setToolbarHidden:NO];
    [super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) goBack:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [mapView release];
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [_signalList release];
    [super dealloc];
}

- (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//    [theMapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//    CLLocationCoordinate2D userCoordinate = userLocation.location.coordinate;
//    for(int i = 1; i<=5;i++)
//    {
//        CGFloat latDelta = rand()*.035/RAND_MAX -.02;
//        CGFloat longDelta = rand()*.03/RAND_MAX -.015;
//        CLLocationCoordinate2D newCoord = { userCoordinate.latitude + latDelta, userCoordinate.longitude + longDelta };
//        MapPoint *mp = [[MapPoint alloc] initWithCoordinate:newCoord title:[NSString stringWithFormat:@"Azam Home %d",i] subTitle:@"Home Sweet Home"];    
//        [theMapView addAnnotation:mp];
//        [mp release];
//
//    }

}

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{    
    CGRect visibleRect = [mapView annotationVisibleRect];

    for(MKAnnotationView *view in views)
    {
        if([view isKindOfClass:[SignalAnnotationView class]])
        {
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
//            [UIView beginAnimations:@"drop" context:NULL];
//            [UIView setAnimationDuration:0.5];
            view.frame = endFrame;
            [UIView commitAnimations];
        }
    }
//    MKAnnotationView *annotationView = [views objectAtIndex:0];
//    id<MKAnnotation> mp = [annotationView annotation];
//    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
//    MKCoordinateRegion region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
//    if (region.center.latitude==0) {
//        region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
//    }
//    [mv setRegion:region animated:YES];

}

- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation
{
//    NSLog(@"%@",ann)
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    NSString *annotationIdentifier = @"SignalViewAnnotation";
//    SignalAnnotationView *pinView = (SignalAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
//    if (!pinView)
//    {
        SignalAnnotationView *pinView = [[[SignalAnnotationView alloc]                     initWithAnnotation:annotation 
                    reuseIdentifier:annotationIdentifier] autorelease];

//        [pinView setPinColor:MKPinAnnotationColorGreen];
//        pinView.animatesDrop = YES;
        pinView.canShowCallout = YES;
    
        UIImageView *houseIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"green_signal.png"]];
        [houseIconView setFrame:CGRectMake(0, 0, 15, 30)];
        pinView.leftCalloutAccessoryView = houseIconView;
        UIButton *detailButton=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//    int testtag=[(MapPoint *)annotation tag];
    detailButton.tag=[(MapPoint *)annotation tag];
        pinView.rightCalloutAccessoryView=detailButton;
        [houseIconView release];        
//    }
//    else
//    {
//        pinView.annotation = annotation;
//    }
    pinView.draggable=NO;
    return pinView;
}

- (void)mapView:(MKMapView *)mapView 
 annotationView:(MKAnnotationView *)annotationView 
didChangeDragState:(MKAnnotationViewDragState)newState 
   fromOldState:(MKAnnotationViewDragState)oldState 
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
    }
}

- (void) locationManager:(CLLocationManager *)manager
        didUpdateHeading:(CLHeading *)newHeading
{
    float heading = newHeading.magneticHeading; //in degrees
    float headingDegrees = (heading*M_PI/180); //assuming needle points to top of iphone. convert to radians
    self.mapView.transform = CGAffineTransformMakeRotation(headingDegrees);
}

//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
//{
//    NSLog(@"Map was moved to %f,%f\n", mapView.region.center.latitude, mapView.region.center.longitude);
//}
- (id)initWithNibNameAndTimingPattern:(NSString *)nibNameOrNil timingPattern:(TimingPattern*)timingPattern agency:(Agency*)agency subSystem:(SubSystem*)subSystem  bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    return self;
}
- (void) changeMapType: (id)sender
{
    if (mapView.mapType == MKMapTypeStandard)
        mapView.mapType = MKMapTypeSatellite;
    else
        mapView.mapType = MKMapTypeStandard;
} 
- (void)mapView:(MKMapView *)eMapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
//    NSLog(@"%@",control.class);
    NSLog(@"%d",control.tag);
    SignalDetailViewController *detailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:control.tag automaticPlayOrNot:NO  bundle:nil] autorelease];
    [detailViewController setTitle:@"Signal Detail"];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end
